package com.ms.education.ucenter.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ms.education.JwtUtils;
import com.ms.education.MD5Util;
import com.ms.education.R;
import com.ms.education.ucenter.entity.User;
import com.ms.education.ucenter.entity.vo.RegisterByPhoneVo;
import com.ms.education.ucenter.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 该表为普通用户，可以访问前台界面 前端控制器
 * </p>
 *
 * @author ms
 * @since 2023-01-12
 */
@RestController
@RequestMapping("/ucenter/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("getById/{id}")
    public R getById(@PathVariable("id") Integer id) {
        User user = userService.getById(id);
        return R.ok().data("user", user);
    }

    /*
    {
      "beginTime": "2023-01-11 19:10:46",
      "endTime": "2023-01-13 19:10:46",
      "highAge": 30,
      "lowAge": 20,
      "nickname": "王"
   }
     */
    @PostMapping("pageUser/{current}/{limit}")
    public R pageUser(@RequestBody User user,
                      @PathVariable("current") long current,
                      @PathVariable("limit") long limit) {
        return userService.pageUser(user, current, limit);
    }

    @PostMapping("deleteByIds")
    public R deleteByIds(@RequestBody Integer[] ids) {
        // TODO 删除与用户关联的数据
        userService.removeBatchByIds(Arrays.asList(ids));
        return R.ok();
    }

    @PostMapping("updateUser")
    public R updateUser(@RequestBody User user) {
        if (!StringUtils.isEmpty(user.getPassword())) {
            user.setPassword(MD5Util.getMD5(user.getPassword()));
        }
        userService.updateById(user);
        return R.ok();
    }

    @PutMapping("saveUser")
    public R saveUser(User user) {
        user.setPassword(MD5Util.getMD5("123456"));
        userService.save(user);
        return R.ok();
    }

    @GetMapping("countRegisterDay/{day}")
    public R countRegisterDay(@PathVariable("day") String day) {
        Integer count = userService.countRegisterDay(day);
        return R.ok().data("count", count);
    }

    @PostMapping("registerByPhone")
    public R registerByPhone(@RequestBody RegisterByPhoneVo register) {
        userService.registerByPhone(register);
        return R.ok();
    }

    @PostMapping("loginByPhone")
    public R loginByPhone(@RequestBody User user) {
        String token = userService.loginByPhone(user);
        return R.ok().data("token", token);
    }

    @PostMapping("loginByCode")
    public R loginByCode(@RequestBody User user) {
        String token = userService.loginByCode(user);
        return R.ok().data("token", token);
    }

    @PostMapping("logout")
    public R logout() {
        StpUtil.logout();
        return R.ok();
    }


    @GetMapping("getLoginInfo")
    public R getLoginInfo() {
        StpUtil.getRoleList();
        StpUtil.getPermissionList();
        User info = userService.getById(Convert.toInt(StpUtil.getLoginId()));
        return R.ok().data("user", info);
    }

    @PostMapping("updatePassword/{mobile}/{newPassword}/{code}")
    public R updatePassword(@PathVariable("mobile") String mobile,
                            @PathVariable("newPassword") String newPassword,
                            @PathVariable("code") String code) {
        userService.updatePassword(mobile, newPassword, code);
        return R.ok();
    }

    @ApiOperation("远程调用班级用户id，并返回分页")
    @GetMapping("pageClassUser/{classId}/{current}/{limit}")
    public R pageClassUser(
            @PathVariable("classId") Integer classId,
            @PathVariable("current") long current,
            @PathVariable("limit") long limit, String name) {
        Page<User> page = userService.pageClassUser(classId, current, limit, name);
        return R.ok().data("rows", page.getTotal()).data("users", page.getRecords());
    }


    @ApiOperation("解锁或封禁账户")
    @SaCheckPermission("user.update")
    @PostMapping("untieOrDisableUser/{userId}/{flag}")
    public R untieOrDisableUser(@PathVariable("userId") Integer userId,
                                @PathVariable("flag") boolean flag) {
        userService.untieOrDisableUser(userId, flag);
        return R.ok();
    }

    @ApiOperation("踢人下线")
    @SaCheckPermission("user.update")
    @PostMapping("makeUserLogout/{userId}")
    public R makeUserLogout(@PathVariable("userId") Integer userId) {
        StpUtil.kickout(userId);
        return R.ok();
    }
}
